import matplotlib.pyplot as plt
import numpy as np
import sympy as sp

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False

# 分析 f(x) = (x^2-4)/(x-2) 在 x->2 的极限
x = sp.symbols('x')
f = (x**2 - 4)/(x - 2)

# 简化函数（x ≠ 2时等价）
f_simplified = sp.simplify(f)
print(f"简化后的函数: {f_simplified}")

# 计算极限
limit_value = sp.limit(f, x, 2)
print(f"x->2时函数的极限: {limit_value}")

# 可视化
x_vals = np.linspace(1, 3, 400)
x_vals = x_vals[x_vals != 2]  # 排除x=2
y_vals = (x_vals**2 - 4) / (x_vals - 2)

plt.figure(figsize=(10, 6))
plt.plot(x_vals, y_vals, 'b-', linewidth=2, label=r'$f(x) = \frac{x^2-4}{x-2}$')
plt.plot(2, 4, 'ro', markersize=8, label='可去间断点')
plt.axhline(y=4, color='r', linestyle='--', alpha=0.7)
plt.axvline(x=2, color='r', linestyle='--', alpha=0.7)
plt.xlabel('x')
plt.ylabel('f(x)')
plt.title('函数在x=2处的极限行为')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()